<template>
  <div>
    <el-button @click="beginSign">开始签约</el-button>
    <el-dialog
      title="签约"
      :visible.sync="dialogVisible"
      width="1520px"
      top="5vh"
      :before-close="handleClose"
    >
      <div class="header">
        <div>开始计时：{{ timing }}</div>
      </div>
      <div class="main">
        <!-- 1 -->
        <div class="box">
          <p class="header-title">第一步：开启录像</p>
          <el-button @click="joinVideo">加入房间</el-button>
          <el-button
            style="margin: 0 10px"
            @click="openRecording"
            :disabled="recordShow"
            >{{ recordText }}</el-button
          >
          <el-button @click="unSubscribe" :disabled="unSubscribeShow"
            >关闭摄像头</el-button
          >
          <div :class="[notVideoShow == true ? '' : 'notIframe']">
            <video
              id="video"
              :class="[notVideoShow == true ? 'iframe' : 'notIframe']"
            ></video>
          </div>
          <div v-if="!notVideoShow">
            <img
              class="notVideo_img"
              src="../../assets/img/notVideo.png"
              alt=""
            />
            <p class="notYet_p">您还没有加入房间~</p>
          </div>
          <!-- :disabled="!notVideoShow" -->
          <el-button class="foot-btn" @click="openSign">开始签约</el-button>
        </div>
        <!-- 2 -->
        <div class="box boxToo" v-if="boxShoOne">
          <p class="header-title">第二步：等待上传文件</p>
          <div class="box-cardHeight">
            <div class="box-card" v-for="(item, index) in files" :key="index">
              <div class="time">{{ item.createTime }}</div>
              <div class="card_flex">
                <p class="card_url">{{ item.oldName }}</p>
                <p class="card_btn" @click="preview(item.fileUrl)">预览</p>
              </div>
            </div>
          </div>
          <p class="title">
            状态：<span style="color: #fb575e">{{ previewState }}</span>
          </p>
          <el-button
            @click="generateContract"
            class="foot-btn"
            v-if="previewBtn"
            >确认无误并生成合同</el-button
          >
        </div>
        <div class="box boxToo" v-if="!boxShoOne">
          <div>
            <img class="notYet_img" src="../../assets/img/notYet.png" alt="" />
            <p class="notYet_p">暂无信息展示，请先完成第一步~</p>
          </div>
        </div>
        <!-- 3 -->
        <div class="box" v-if="boxShoToo">
          <p class="header-title">第三步：等待上传合同</p>
          <div class="box-cardHeight">
            <div
              class="box-card"
              v-for="(item, index) in filesContract"
              :key="index"
            >
              <div class="time">{{ item.createTime }}</div>
              <div class="card_flex">
                <p class="card_url">{{ item.oldName }}</p>
                <p class="card_btn" @click="preview(item.fileUrl)">预览</p>
              </div>
            </div>
          </div>
          <p class="title">
            状态：<span style="color: #fb575e">{{ contractState }}</span>
          </p>
          <div class="foot-threeBtn">
            <el-button
              style="margin-right: 15px; width: 150px"
              v-if="contractBtn"
              @click="confirmed"
              >确认无误</el-button
            >
            <el-button
              style="margin-left: 15px; width: 150px"
              @click="againSginble = true"
              v-if="contractBtn"
              >重签</el-button
            >
          </div>
        </div>
        <div class="box" v-if="!boxShoToo">
          <div>
            <img class="notYet_img" src="../../assets/img/notYet.png" alt="" />
            <p class="notYet_p">暂无信息展示，请先完成第二步~</p>
          </div>
        </div>
      </div>
      <div>
        <el-button class="end-btn" @click="completeSgin" v-if="agreeBtn"
          >完成签约</el-button
        >
      </div>
      <el-dialog
        width="40%"
        title="预览文件"
        :visible.sync="innerVisible"
        append-to-body
      >
        <iframe class="previewImg" :src="previewUrl" alt="" />
      </el-dialog>
      <el-dialog
        width="25%"
        title="提示"
        :visible.sync="againSginble"
        append-to-body
        :before-close="againSginClose"
      >
        <el-form
          ref="formInline"
          :rules="rules"
          :model="formInline"
          label-width="80px"
        >
          <el-form-item label="重签原因" prop="remake">
            <el-input
              v-model="formInline.remake"
              type="textarea"
              placeholder="重签原因"
            ></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer">
          <el-button style="margin-right: 10px" @click="againSginGb"
            >取 消</el-button
          >
          <el-button type="primary" style="margin-left: 10px" @click="againSgin"
            >确定</el-button
          >
        </span>
      </el-dialog>
      <el-dialog
        width="30%"
        title="生成合同"
        :visible.sync="whetherSignble"
        append-to-body
        style="text-align: center"
        :before-close="whetherSignClose"
      >
        <!-- <span style="font-weight: bold; font-size: 16px">{{
          whetherSignText
        }}</span> -->
        <el-form
          ref="form"
          :rules="rulesForm"
          :model="form"
          label-width="150px"
        >
          <el-form-item label="产权证号" prop="propertyCode">
            <el-input
              v-model="form.propertyCode"
              type="text"
              placeholder="产权证号"
            ></el-input>
          </el-form-item>
          <el-form-item label="合同编号" prop="code">
            <el-input
              v-model="form.code"
              type="text"
              placeholder="合同编号"
            ></el-input>
          </el-form-item>
          <el-form-item label="签约地址" prop="signAddress">
            <el-input
              v-model="form.signAddress"
              type="text"
              placeholder="签约地址"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否需要签字页" prop="remake">
            <el-select v-model="form.signature" placeholder="请选择">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="whetherSignQx" style="margin-right: 10px"
            >取 消</el-button
          >
          <el-button
            type="primary"
            @click="whetherSign"
            style="margin-left: 10px"
            >确 定</el-button
          >
        </span>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
import {
  // getSignCheck,
  // postObtainRtc,
  getFingers,
  postCameraStart,
  postCameraDown,
  postConfirmFingers,
  getUploads,
  postConfirmUploads,
  // postGuarantee
  // postResign,
  postAgree,
} from "../../../src/assets/js/api";
export default {
  name: "ChannelSign",
  props: ["orderNumber"],

  data() {
    return {
      aliWebrtc: new window.AliRtcEngine(),
      dialogVisible: false,
      innerVisible: false,
      whetherSignble: false,
      againSginble: false,
      recordText: "开始录制",
      returnTime: "", // 返回的开始时间和结束时间
      nowTime: "", // 开始时间
      timing: "", // 计时器
      endTime: "", // 结束时间
      hour: 0, //定义时，分，秒，毫秒并初始化为0；
      minute: 0,
      ms: 0,
      second: 0, //秒
      time: "",
      boxShoOne: false,
      boxShoToo: false,
      notVideoShow: false,
      AliyunHtml: "../aliyun/index.html",
      signId: "",
      previewState: "上传中",
      contractState: "上传中",
      timerFingers: "",
      timerContract: "",
      files: [],
      filesContract: [],
      isRouterAlive: true,
      userId: "",
      showId: 1,
      authInfo: {},
      recordType: "1",
      recordShow: true,
      unSubscribeShow: true,
      previewUrl: "",
      whetherSignText: "",
      // whetherSignShow: true,
      previewBtn: false,
      contractBtn: false,
      agreeBtn: false,
      options: [
        {
          value: 0,
          label: "否",
        },
        {
          value: 1,
          label: "是",
        },
      ],
      formInline: {
        remake: "",
      },
      form: {
        id: "",
        propertyCode: "",
        code: "",
        signAddress: "",
        signature: 1,
      },
      rules: {
        remake: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
        ],
      },
      rulesForm: {
        propertyCode: [
          { required: true, message: "请输入产权证号", trigger: "blur" },
        ],
        code: [{ required: true, message: "请输入合同编号", trigger: "blur" }],
      },
      token: "",
    };
  },
  created() {
    this.onPublisher();
    this.token = localStorage.getItem("token");
  },
  mounted() {
    // this.timerFingers = setInterval(this.openSign, 1000);
  },
  destroyed() {
    clearTimeout(this.timerFingers);
    clearTimeout(this.timerContract);
  },
  methods: {
    // 点击开始签约
    beginSign() {
      this.dialogVisible = true;
      // postObtainRtc(23).then((res) => {
      //   if (res.code == 200) {
      //     this.authInfo = res.data;
      //     this.showId = res.data;
      //   }
      // });
      this.axios
        .get(`/sys/contract/sign/check/${this.showId}/${this.orderNumber}`, {
          //请求头配置
          headers: { token: this.token },
        })
        .then((res) => {
          if (res.data.code == 200 && res.data.data != null) {
            this.dialogVisible = true;
            this.signId = res.data.data;
          }
        });
    },
    // 加入房间
    joinVideo() {
      let userName = "大数据";

      this.aliWebrtc.joinChannel(this.authInfo, userName).then(
        () => {
          // 入会成功

          this.subscribe();
        },
        (error) => {
          // 入会失败，打印错误内容，可以看到失败原因
          console.log(error, "123");
        }
      );
    },
    // 接受本地流回调
    onPublisher() {
      this.aliWebrtc.on("onPublisher", (publisher) => {
        this.userId = publisher.userId;
      });
    },
    // 订阅远程流
    subscribe() {
      this.aliWebrtc.subscribe(this.userId).then(
        (userId) => {
          console.log(userId);
          this.openVideo();
        },
        (error) => {
          this.$message.error("加入房间失败");
          console.log(error, "000");
        }
      );
    },
    // 取消订阅
    unSubscribe() {
      this.aliWebrtc.unSubscribe(this.userId).then(
        () => {
          this.stopVideo();
          this.notVideoShow = false;
          this.unSubscribeShow = true;
        },
        (error) => {
          console.log(error.message, "p");
        }
      );
    },
    // 回显摄像头
    openVideo() {
      let video = document.getElementById("video");

      this.aliWebrtc.subscribe(this.userId).then(
        (userId) => {
          this.aliWebrtc.setDisplayRemoteVideo(
            userId, // 用户ID
            video, // html中用于显示stream对象的video元素
            1 // 1表示摄像头流（大流和小流），2表示屏幕分享流
          );
          this.notVideoShow = true;
          this.recordShow = false;
          this.unSubscribeShow = false;
        },
        (error) => {
          console.log(error.message);
        }
      );
      // this.aliWebrtc
      //   .startPreview(
      //     video // html中的video元素
      //   )
      //   .then(() => {})
      //   .catch((i) => {
      //     // 预览失败
      //     console.log(i, "9999");
      //   });
    },
    // 关闭摄像头
    stopVideo() {
      this.aliWebrtc
        .stopPreview()
        .then(() => {})
        .catch((error) => {
          // 结束预览失败
          console.log(error, "失败");
        });
    },
    // 开始录制
    openRecording() {
      if (this.recordType == "1") {
        postCameraStart(23).then((res) => {
          if (res.code == 200) {
            this.recordText = "结束录制";
            this.recordType = "2";
            this.recordShow = true;
            this.$message.success(res.message);
          }
        });
      } else {
        postCameraDown(23).then((res) => {
          if (res.code == 200) {
            this.recordText = "开始录制";
            this.recordShow = true;
            this.$message.success(res.message);
          }
        });
      }
    },
    // 开始签约
    openSign() {
      this.boxShoOne = true;
      this.getFingers();
      this.time = setInterval(this.timer, 50);
      this.timerFingers = setInterval(this.getFingers, 6000);
    },
    getFingers() {
      // this.isRouterAlive = false;
      getFingers(this.signId).then((res) => {
        this.files = res.data.files;
        // this.isRouterAlive = true;
        if (res.data.state == null) {
          this.previewState = "上传中";
        } else {
          this.previewState = "上传完成";
          this.previewBtn = true;
        }

        if (res.data.state !== null) {
          clearTimeout(this.timerFingers);
        }
      });
    },
    // 点击预览
    preview(item) {
      this.previewUrl = item;
      this.innerVisible = true;
    },
    // 生成合同
    generateContract() {
      // 确认合同无误
      postConfirmFingers(this.signId).then((res) => {
        if (res.code == 200) {
          this.whetherSignble = true;
        }
      });
    },
    whetherSign() {
      this.form.id = this.signId;
      this.$refs.form.validate((valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "正在生成合同，请稍等",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          this.axios
            .post(`/sys/contract/sign/generate/guarantee`, this.form, {
              timeout: 60000,
            })
            .then((res) => {
              loading.close();
              this.whetherSignble = false;
              this.$refs.form.resetFields();
              if (res.data.code == 200) {
                this.boxShoToo = true;
                this.getContract();
                this.timerContract = setInterval(this.getContract, 6000);
                this.$message.success(res.data.message);
              } else {
                this.$message.error(res.data.message);
              }
            });
        }
      });
    },
    whetherSignQx() {
      this.whetherSignble = false;
      this.$refs.form.resetFields();
    },
    whetherSignClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
          this.$refs.form.resetFields();
        })
        .catch(() => {});
    },
    // 第三步获取合同
    getContract() {
      getUploads(this.signId).then((res) => {
        this.filesContract = res.data.files;
        // this.isRouterAlive = true;
        if (res.data.state == null) {
          this.contractState = "上传中";
        } else {
          this.contractState = "上传完成";
          this.contractBtn = true;
        }

        if (res.data.state !== null) {
          clearTimeout(this.timerContract);
        }
      });
    },
    // 第三步确认无误
    confirmed() {
      postConfirmUploads(this.signId).then((res) => {
        if (res.code == 200) {
          this.$message.success(res.message);
          this.agreeBtn = true;
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 重签
    againSgin() {
      this.$refs.formInline.validate((valid) => {
        if (valid) {
          this.axios
            .post(`/sys/contract/sign/resign/${this.signId}`, this.formInline, {
              //请求头配置
              headers: { token: this.token },
            })
            .then((res) => {
              console.log(res);
              this.againSginble = false;
              this.$refs.formInline.resetFields();
            });
        }
      });

      // postResign(this.signId).then((res) => {
      //   if (res.code == 200) {
      //     // this.dialogVisible = false
      //   }
      // });
    },
    // 关闭重签
    againSginGb() {
      this.againSginble = false;
      this.$refs.formInline.resetFields();
    },
    againSginClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
          this.$refs.formInline.resetFields();
        })
        .catch(() => {});
    },
    // 完成签约
    completeSgin() {
      clearInterval(this.time);
      postAgree(this.signId).then((res) => {
        this.dialogVisible = false;
        if (res.code == 200) {
          this.$message.success(res.message);
        } else {
          this.$message.error(res.message);
        }
      });
    },
    // 计时器
    timer() {
      //定义计时函数
      this.ms = this.ms + 50; //毫秒
      if (this.ms >= 1000) {
        this.ms = 0;
        this.second = this.second + 1; //秒
      }
      if (this.second >= 60) {
        this.second = 0;
        this.minute = this.minute + 1; //分钟
      }
      if (this.minute >= 60) {
        this.minute = 0;
        this.hour = this.hour + 1; //小时
      }
      this.timing =
        this.toDub(this.hour) +
        ":" +
        this.toDub(this.minute) +
        ":" +
        this.toDub(this.second); /*+""+this.toDubms(this.ms)+"毫秒"*/
      if (this.timing > "00:29:59") {
        clearInterval(this.time);
        this.$alert("已经超过签约时间，请重签！", "提示", {
          confirmButtonText: "确定",
          callback: () => {
            this.dialogVisible = false;
            this.clear();
          },
        });
      }
    },
    clear() {
      clearInterval(this.time);
      clearTimeout(this.timerFingers);
      clearTimeout(this.timerContract);
      this.timing = "";
      this.hour = 0;
      this.minute = 0;
      this.ms = 0;
      this.second = 0;
      this.time = "00:00:00";
      this.recordType = "1";
      this.stopVideo();
    },
    toDub(n) {
      if (n < 10) {
        return "0" + n;
      } else {
        return "" + n;
      }
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(() => {
          done();
          this.clear();
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped type="less">
.main {
  width: 100%;
  height: 600px;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
}
.header {
  width: 100%;
  height: 50px;
  display: flex;
  justify-content: space-between;
  box-sizing: border-box;
}
.header div {
  flex: 1;
  line-height: 50px;
}
.box {
  flex: 1;
  padding: 0 10px;
  position: relative;
}
.boxToo {
  border-left: 1px #999999 solid;
  border-right: 1px #999999 solid;
}
.notYet_p {
  font-size: 16px;
  font-family: Microsoft YaHei;
  font-weight: 400;
  color: #343434;
  line-height: 21px;
}
.notYet_img {
  width: 154px;
  height: 154px;
  margin-top: 160px;
}
.notVideo_img {
  width: 143px;
  height: 104px;
  margin-top: 130px;
}
.el-button {
  margin: 20px 0;
}
.iframe {
  width: 100%;
  height: 400px;
}
.notIframe {
  width: 0;
  height: 0;
}
.title {
  margin: 20px 0;
  font-size: 15px;
}
.header-title {
  font-size: 15px;
  font-family: PingFang SC;
  font-weight: bold;
  color: #333333;
  text-align: left;
}
.box-cardHeight {
  height: 450px;
  overflow: auto;
}
.box-card {
  padding: 20px;
  margin-top: 20px;
  border-radius: 5px;
  background-color: #f8f8f8;
}
.time {
  text-align: left;
  font-size: 12px;
  font-family: PingFang SC;
  color: #999999;
}
.card_flex {
  display: flex;
  margin-top: 10px;
}
.card_url {
  flex: 1;
  font-size: 14px;
  font-family: Microsoft YaHei;
  color: #333333;
  text-align: left;
}
.card_btn {
  text-align: right;
  color: #52aaf8;
  font-size: 12px;
  border: 1px #52aaf8 solid;
  border-radius: 5px;
  padding: 0 5px;
  height: 20px;
  line-height: 20px;
}
.card_btn:hover {
  cursor: pointer;
}
.foot-btn {
  position: absolute;
  bottom: 0;
  width: 200px;
  left: 150px;
}
.foot-threeBtn {
  position: absolute;
  bottom: 0;
  left: 85px;
}
.end-btn {
  width: 360px;
  color: white;
  background-color: #3b9df8;
}
.box-cardHeight::-webkit-scrollbar {
  /*滚动条整体样式*/
  width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
  height: 1px;
}
.box-cardHeight::-webkit-scrollbar-thumb {
  /*滚动条里面小方块*/
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 5px #52aaf8;
  background: #52aaf8;
}
.box-cardHeight::-webkit-scrollbar-track {
  /*滚动条里面轨道*/
  -webkit-box-shadow: inset 0 0 5px #ededed;
  border-radius: 5px;
  background: #ededed;
}
.previewImg {
  width: 100%;
  height: auto;
}
::v-deep .el-dialog__footer {
  text-align: center;
}
::v-deep .el-select {
  width: 100%;
}
</style>